//
//  DownloadCell.swift
//  下载Cell
//
//  Created by smile on 2019/4/28.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//发布订阅框架
import SwiftEventBus

class DownloadCell: BaseTableViewCell {
    static var NAME = "DownloadCell"
    
    /// 标题
    @IBOutlet weak var lbTitle: UILabel!
    
    /// 更多信息
    @IBOutlet weak var lbInfo: UILabel!
    
    /// 进度条
    @IBOutlet weak var pvProgress: UIProgressView!

    var data:DownloadInfo!
    
    func bindData(_ data:DownloadInfo) {
        self.data=data;
        
        //根据Id获取业务数据
        let song=ORMUtil.shared().findSongByUri(data.id)
        
        if let song = song {
            lbTitle.text=song.title
        }else{
            //TODO 如果为空就表示逻辑有问题
        }
        
        setDownloadCallback()
        
        refresh(false)
    }
    
    func setDownloadCallback() {
        weak var weakSelf = self
        
        //设置下载回调
        data.downloadBlock={
            downloadInfo in
            weakSelf?.refresh(true)
        }
    }
    
    /// 刷新状态
    ///
    /// - Parameter isDownloadManagerNotify: <#isDownloadManagerNotify description#>
    func refresh(_ isDownloadManagerNotify:Bool) {
        switch data.status {
        case .paused:
            pvProgress.isHidden=true
            lbInfo.text="已暂停，点击继续下载"
        case .error:
            pvProgress.isHidden=true
            lbInfo.text="下载失败，点击重试"
        case .downloading,.prepareDownload:
            pvProgress.isHidden=false
            //进度
            if data.size>0 {
                
                //计算下载进度百分比
                //0~1之间
                pvProgress.progress=Float(Double(data.progress)/Double(data.size))
                
                //格式化进度
                let start=FileUtil.formatFileSize(data.progress)
                let size=FileUtil.formatFileSize(data.size)
                let progressString="\(start)/\(size)"
                lbInfo.text=progressString
            }
        case .completed:
            //该界面不会显示
            //下载完成的任务
            //所以要发送通知
            //让下载列表接收到
            //然后移除
            
            publishDownloadComplete(isDownloadManagerNotify)
            break;
        case .wait:
            pvProgress.isHidden=true
            lbInfo.text="等待中，点击暂停"
        default:
            //未下载状态
            //当点击删除后
            //是这种状态
            publishDownloadComplete(isDownloadManagerNotify)
        }
        
    }
    
    /// 下载完成后发送通知
    ///
    /// - Parameter isDownloadManagerNotify: <#isDownloadManagerNotify description#>
    func publishDownloadComplete(_ isDownloadManagerNotify:Bool) {
        if isDownloadManagerNotify {
            SwiftEventBus.post(DOWNLOAD_STATUS_CHANGED)
        }

    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
